<template>
	<view class="content">
		<view class="search-box">
			<!-- mSearch组件 如果使用原样式，删除组件元素-->
			<mSearch class="mSearch-input-box" :mode="2" button="inside" :placeholder="defaultKeyword" @search="doSearch(false)" @input="inputChange" @confirm="doSearch(false)" v-model="keyword"></mSearch>
			<!-- 原样式 如果使用原样式，恢复下方注销代码 -->
			<!-- 			
			<view class="input-box">
				<input type="text" :placeholder="defaultKeyword" @input="inputChange" v-model="keyword" @confirm="doSearch(false)"
				 placeholder-class="placeholder-class" confirm-type="search">
			</view>
			<view class="search-btn" @tap="doSearch(false)">搜索</view> 
			 -->
			<!-- 原样式 end -->
		</view>
		<view class="search-keyword" @touchstart="blur">
			<scroll-view class="keyword-list-box" v-show="isShowSuggestKeywords" scroll-y>
				<view class="keyword-entry" hover-class="keyword-entry-tap" v-for="row in suggestKeywords" :key="row.keyword">
					<view class="keyword-text" @tap="doSearch(row.keyword)">
						<rich-text :nodes="row.htmlStr"></rich-text>
					</view>
					<view class="keyword-img" @tap="setKeyword(row)">
						<image src="/static/search/back.png"></image>
					</view>
				</view>
			</scroll-view>
			<scroll-view class="keyword-box" v-show="!isShowSuggestKeywords" scroll-y>
				<view class="keyword-block" v-if="searchHistoryKeywords.length > 0">
					<view class="keyword-list-header">
						<view>历史搜索</view>
						<view>
							<image @tap="deleteSearchHistory" src="/static/search/delete.png"></image>
						</view>
					</view>
					<view class="keyword">
						<view v-for="(keyword,index) in searchHistoryKeywords" :key="index" @tap="doSearch(keyword)" @longtap="deleteOneHistory(index, keyword)">{{keyword}}</view>
					</view>
				</view>
				<view class="keyword-block">
					<view class="keyword-list-header">
						<view>热门搜索</view>
						<view>
							<image @tap="hotToggle" :src="'/static/search/attention'+forbid+'.png'"></image>
						</view>
					</view>
					<view class="keyword" v-if="forbid==''">
						<view v-for="(keyword,index) in hotSearchKeywords" @tap="doSearch(keyword)" :key="index">{{keyword}}</view>
					</view>
					<view class="hide-hot-tis" v-else>
						<view>当前搜热门搜索已隐藏</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import { doPostJson, doGet, showInfoToast, HAS_USER_INFO, GOODS_SEARCH_HISTORY_KEYWORDS } from '@/common/util.js'
	import * as ResponseStatus from '@/common/response-status.js'
	import mSearch from '@/components/mehaotian-search-revision/mehaotian-search-revision.vue'
	export default {
		data() {
			return {
				defaultKeyword: '请输入关键字',
				keyword: '',
				searchHistoryKeywords: [],
				hotSearchKeywords: [],
				suggestKeywords: [],
				forbid: '',
				isShowSuggestKeywords: false,
				hasUserInfo: false
			}
		},
		onLoad() {
			this.hasUserInfo = uni.getStorageSync(HAS_USER_INFO)
			this.init()
		},
		components: {
			mSearch
		},
		methods: {
			init() {
				this.loadSearchHistory()
				this.loadHotSearch()
			},
			blur(){
				uni.hideKeyboard()
			},
			loadSearchHistory() {
				if (this.hasUserInfo) {
					// 用户已经登录，则显示用户的搜索历史
					doGet('/search-history/user/his-keys/15', {}, {}, true).then(response => {
						let [err, res] = response
						if (res.data.code === ResponseStatus.OK) {
							this.searchHistoryKeywords = res.data.data
							if (this.searchHistoryKeywords.length > 0) {
								let idx = Math.floor(Math.random() * this.searchHistoryKeywords.length)
								this.defaultKeyword = this.searchHistoryKeywords[idx]
							}
						}
					}).catch(error => {
						console.log(error)
					})
				} else {
					// 否则显示本地存储的历史
					uni.getStorage({
						key: GOODS_SEARCH_HISTORY_KEYWORDS,
						success: (res) => {
							this.searchHistoryKeywords = JSON.parse(res.data)
							if (this.searchHistoryKeywords.length > 0) {
								let idx = Math.floor(Math.random() * this.searchHistoryKeywords.length)
								this.defaultKeyword = this.searchHistoryKeywords[idx]
							}
						}
					})
				}
			},
			loadHotSearch() {
				doGet('/search-history/user/hot-keys/15', {}, {}, false).then(response => {
					let [err, res] = response
					if (res.data.code === ResponseStatus.OK) {
						this.hotSearchKeywords = res.data.data
						if (this.defaultKeyword === '请输入关键字' && this.hotSearchKeywords.length > 0) {
							let idx = Math.floor(Math.random() * this.hotSearchKeywords.length)
							this.defaultKeyword = this.hotSearchKeywords[idx]
						}
					}
				}).catch(error => {
					console.log(error)
				})
			},
			inputChange(event) {
				/**
				//兼容引入组件时传入参数情况
				var keyword = event.detail?event.detail.value:event
				if (!keyword) {
					this.suggestKeywords = []
					this.isShowSuggestKeywords = false
					return
				}
				this.isShowSuggestKeywords = true
				// 输入时即时搜索关键字
				uni.request({
					url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword,
					success: (res) => {
						this.suggestKeywords = this.drawCorrelativeKeyword(res.data.result, keyword)
					}
				})
				**/
			},
			//高亮关键字
			drawCorrelativeKeyword(keywords, keyword) {
				var len = keywords.length,
					keywordArr = []
				for (var i = 0; i < len; i++) {
					var row = keywords[i]
					//定义高亮#9f9f9f
					var html = row[0].replace(keyword, "<span style='color: #9f9f9f;'>" + keyword + "</span>")
					html = '<div>' + html + '</div>'
					var tmpObj = {
						keyword: row[0],
						htmlStr: html
					}
					keywordArr.push(tmpObj)
				}
				return keywordArr
			},
			doSearch(key) {
				key = key ? key : this.keyword ? this.keyword : this.defaultKeyword
				if (!key) {
					showInfoToast('请输入关键字')
					return
				}
				this.keyword = key
				this.saveSearchHistory(key)
				uni.navigateTo({
					url: `/pages/product/list?keywords=${this.keyword}&pageTitle=${this.keyword}`
				})
			},
			saveSearchHistory(keywords) {
				if (this.hasUserInfo) {
					doPostJson('/search-history/user/save', {
						keywords: keywords,
						searchType: 0
					}, {}, true).then(response => {
						let [err, res] = response
						if (res.data.code === ResponseStatus.OK) {
							let keywordIdx = this.searchHistoryKeywords.indexOf(keywords)
							if (keywordIdx < 0) {
								this.searchHistoryKeywords.splice(0, 0, keywords)
							} else {
								this.searchHistoryKeywords.splice(keywordIdx, 1)
								this.searchHistoryKeywords.splice(0, 0, keywords)
							}
						}
					}).catch(error => {
						console.log(error)
					})
				} else {
					uni.getStorage({
						key: GOODS_SEARCH_HISTORY_KEYWORDS,
						success: (res) => {
							var historyKeywords = JSON.parse(res.data)
							var findIndex = historyKeywords.indexOf(keywords)
							if (findIndex == -1) {
								historyKeywords.unshift(keywords)
							} else {
								historyKeywords.splice(findIndex, 1)
								historyKeywords.unshift(keywords)
							}
							historyKeywords.length > 15 && historyKeywords.pop()
							uni.setStorage({
								key: GOODS_SEARCH_HISTORY_KEYWORDS,
								data: JSON.stringify(historyKeywords)
							})
							this.searchHistoryKeywords = historyKeywords
						},
						fail: (e) => {
							var historyKeywords = [keywords]
							uni.setStorage({
								key: GOODS_SEARCH_HISTORY_KEYWORDS,
								data: JSON.stringify(historyKeywords)
							})
							this.searchHistoryKeywords = historyKeywords
						}
					})
				}
			},
			setKeyword(data) {
				this.keyword = data.keyword
			},
			deleteOneHistory(index, keyword) {
				uni.showModal({
					content: '确定删除该搜索记录？',
					success: (res) => {
						if (res.confirm) {
							if (this.hasUserInfo) {
								doGet('/search-history/user/remove-by-keyword/' + keyword, {}, {}, true).then(response => {
									let [err, res] = response
									if (res.data.code === ResponseStatus.OK) {
										this.searchHistoryKeywords.splice(index, 1)
									}
								}).catch(error => {
									console.log(error)
								})
							} else {
								this.searchHistoryKeywords.splice(index, 1)
								uni.setStorage({
									key: GOODS_SEARCH_HISTORY_KEYWORDS,
									data: JSON.stringify(this.searchHistoryKeywords)
								})
							}
						}
					}
				})
			},
			deleteSearchHistory() {
				uni.showModal({
					content: '确定清除历史搜索记录？',
					success: (res) => {
						if (res.confirm) {
							uni.removeStorage({
								key: GOODS_SEARCH_HISTORY_KEYWORDS
							})
							if (this.hasUserInfo) {
								doGet('/search-history/user/remove', {}, {}, true).then(response => {
									let [err, res] = response
									if (res.data.code === ResponseStatus.OK) {
										this.searchHistoryKeywords = []
									}
								}).catch(error => {
									console.log(error)
								})
							} else {
								this.searchHistoryKeywords = []
							}
						}
					}
				})
			},
			hotToggle() {
				this.forbid = this.forbid ? '' : '_forbid'
			}
		}
	}
</script>
<style>
	view{display:block;}
	.search-box {background-color:rgb(242,242,242);padding:15upx 2.5%;display:flex;justify-content:space-between;}
	.search-box .mSearch-input-box{width: 100%;}
	.search-box .input-box {width:85%;flex-shrink:1;display:flex;justify-content:center;align-items:center;}
	.search-box .search-btn {width:15%;margin:0 0 0 2%;display:flex;justify-content:center;align-items:center;flex-shrink:0;font-size:28upx;color:#fff;background:linear-gradient(to right,#ff9801,#ff570a);border-radius:60upx;}
	.search-box .input-box>input {width:100%;height:60upx;font-size:32upx;border:0;border-radius:60upx;-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0 3%;margin:0;background-color:#ffffff;}
	.placeholder-class {color:#9e9e9e;}
	.search-keyword {width:100%;background-color:rgb(242,242,242);}
	.keyword-list-box {height:calc(100vh - 110upx);padding-top:10upx;border-radius:20upx 20upx 0 0;background-color:#fff;}
	.keyword-entry-tap {background-color:#eee;}
	.keyword-entry {width:94%;height:80upx;margin:0 3%;font-size:30upx;color:#333;display:flex;justify-content:space-between;align-items:center;border-bottom:solid 1upx #e7e7e7;}
	.keyword-entry image {width:60upx;height:60upx;}
	.keyword-entry .keyword-text,.keyword-entry .keyword-img {height:80upx;display:flex;align-items:center;}
	.keyword-entry .keyword-text {width:90%;}
	.keyword-entry .keyword-img {width:10%;justify-content:center;}
	.keyword-box {height:calc(100vh - 110upx);border-radius:20upx 20upx 0 0;background-color:#fff;}
	.keyword-box .keyword-block {padding:10upx 0;}
	.keyword-box .keyword-block .keyword-list-header {width:94%;padding:10upx 3%;font-size:27upx;color:#333;display:flex;justify-content:space-between;}
	.keyword-box .keyword-block .keyword-list-header image {width:40upx;height:40upx;}
	.keyword-box .keyword-block .keyword {width:94%;padding:3px 3%;display:flex;flex-flow:wrap;justify-content:flex-start;}
	.keyword-box .keyword-block .hide-hot-tis {display:flex;justify-content:center;font-size:28upx;color:#6b6b6b;}
	.keyword-box .keyword-block .keyword>view {display:flex;justify-content:center;align-items:center;border-radius:60upx;padding:0 20upx;margin:10upx 20upx 10upx 0;height:60upx;font-size:28upx;background-color:rgb(242,242,242);color:#6b6b6b;}
</style>
